package com.leyou.trade.service.impl;

import com.leyou.trade.entity.Order;
import com.leyou.trade.service.OrderService;
import com.leyou.trade.service.PayService;
import com.leyou.trade.utils.PayHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    private final PayHelper payHelper;

    private final OrderService orderService;


    public PayServiceImpl(PayHelper payHelper, OrderService orderService) {
        this.payHelper = payHelper;
        this.orderService = orderService;
    }


    @Override
    public String getPayUrl(Long id) {

        Order order = this.orderService.getById(id);

        Long actualFee = order.getActualFee();

       return this.payHelper.getPayUrl(id,/*actualFee*/1L, "乐优商城商品");
    }

    @Override
    public void handleWxNotify(Map<String, String> resultMap) {

        // 1.业务标示校验
        payHelper.checkResultCode(resultMap);
        // 2.签名校验
        payHelper.checkResponseSignature(resultMap);

        // 3.订单状态校验（保证幂等，防止重复通知）
        String outTradeNo = resultMap.get("out_trade_no");
        String totalFee = resultMap.get("total_fee");
        if (StringUtils.isBlank(outTradeNo) || StringUtils.isBlank(totalFee)) {
            // 数据有误
            throw new RuntimeException("响应数据有误，订单金额或编号为空！");
        }
        Long orderId = Long.valueOf(outTradeNo);
        Order order = orderService.getById(orderId);
        if (order.getStatus()!=1) {
            // 说明订单已经支付过了，属于重复通知，直接返回
            return;
        }

        // 4.订单金额校验
        Long total = Long.valueOf(totalFee);
        if (!total.equals(1L/*order.getActualFee()*/)) {
            throw new RuntimeException("订单金额有误，我要报警了！");
        }

        // 5.修改订单状态，更新状态和支付时间两个字段
        this.orderService.update().set("status", 2).set("pay_time", new Date())
                // 条件包括订单id和订单状态必须为1，乐观锁保证幂等
                .eq("order_id", orderId).eq("status", 1).update();
        log.info("处理微信支付通知成功！{}", resultMap);
    }
}
